<title>数据填报</title>
<div class="layui-card layadmin-header">
	<div class="layui-breadcrumb" lay-filter="breadcrumb" lay-separator=">">
        <a lay-href=""><i class="layui-icon layui-icon-locate"></i>您当前的位置：</a>
		<a><cite class="first-breadcrumb">考勤管理</cite></a>
        <a><cite class="second-breadcrumb">考勤填报</cite></a>
        <a><cite class="third-breadcrumb"></cite></a>
	</div>
</div>

<div class="layui-fluid clearfix top-part">
    <div class="layui-row">
        <div class="layui-col-md12">
            <div class="layui-card left-card">
                <div class="layui-card-header">
                    <img src="../../../../dist/style/res/formFill/tem-task.png" class="card-header-icon"/>
                    <span class="card-header-title">任务列表—<span style="color: #FF5722;">请点击任务后，在下方表格进行填表</span></span>
                </div>
                <div class="layui-card-body test-table-simple1Box">
                    <table class="layui-hide task-list" id="test-table-simple1" lay-filter="test-table-simple1">
                    </table>
                </div>
            </div>
        </div>
        <div class="layui-col-md3 layui-hide">
            <div class="layui-card right-card">
                <div class="layui-card-header undo-task">
                    <img src="../../../../dist/style/res/formFill/tem-task.png" class="card-header-icon"/>
                </div>
                <div class="task-ul">
                    <ul class="scroll"></ul>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="layui-fluid">
    <div class="layui-col-md12">
        <div class="layui-card select-form-box">
            <div class="layui-card-header clearfix select-form-header">
                <div class="card-header-left left">
                    <img src="../../../../dist/style/res/formFill/tem-task.png" class="card-header-icon"/>
                    <div class="layui-inline custom-card-header">
                        <span class="card-header-title">填报表单详情</span>
                        <span class="layui-title-mid layui-hide">-</span>
                        <span class="card-header-subtitle"></span>
                    </div>
                </div>
                <div class="card-header-right right card-header-kq" style="display: none;">
                    <div class="kq-info-title">
                        <span>填报单位：</span><span class="c-unit"></span>&nbsp;&nbsp;
                        <span>考勤日期：</span><span class="c-startDate"></span>~<span class="c-endDate"></span>
                    </div>
                    <button class="layui-btn layui-btn-normal btn-subform T-btn" data-target="submit-kq">提交表单</button>
                    <button class="layui-btn layui-btn-normal btn-saveform T-btn" data-target="save-kq">保存表单</button>
                    <button class="layui-btn layui-btn-primary btn-colla T-btn" data-target="colla">
                        <i class="layui-icon layui-icon-up"></i>
                    </button>
                </div>
                <div class="card-header-right right card-header-other" style="display: none;">
                    <button class="layui-btn layui-btn-normal btn-subform T-btn" id="btn-subform" data-target="submit">提交表单</button>
                    <button class="layui-btn layui-btn-normal btn-saveform T-btn" id="btn-saveform" data-target="save">保存表单</button>
                    <button class="layui-btn layui-btn-normal btn-export T-btn" id="btn-export" data-target="export">导出模板</button>
                    <button class="layui-btn layui-btn-normal btn-import T-btn" id="btn-import" data-id="" data-taskid="" data-target="import">导入数据</button>
                    <button class="layui-btn layui-btn-primary btn-colla T-btn" data-target="colla">
                        <i class="layui-icon layui-icon-up"></i>
                    </button>
                </div>
            </div>
            <div class="layui-tab layui-tab-card otherForm-content layui-form" lay-filter='custom-tabSwitch'>
                <ul class="layui-tab-title form-tab-title"></ul>
                <div class="unit-radios" id="dept"></div>
                <div class="layui-tab-content form-tab-content"></div>
            </div>
            <div id="fill-form-kqform" class="kqform kqform-content">
                <div class="no-data-tips" style="margin-top: 50px;">
                    <img src="/src/style/res/about/empty.png">
                    <p style="color:#DBDBDB;">暂无数据</p>
                </div>
            </div>
        </div>
    </div>
</div>
<style>
    .top-part{
        margin: 12px 0 20px 0;
    }
    .left-card, .right-card, .layui-card{
        border-radius: 4px;
    }
    .right-card{
        height: 425px;
        background: #fff;
    }
    .scroll{
        overflow-y: scroll;
    }
    .task-ul{
        height: 345px;
        padding: 18px 0;
    }
    .task-ul ul{
        height: 100%;
        font-size: 14px;
    }
    .task-ul ul li{
        height: 32px;
        line-height: 32px;
        padding: 0 25px 0 20px;
        cursor: default;
    }
    .task-ul ul li+li:hover{
        background: #DCE7F4;
    }
    .layui-table td, .layui-table th{
        text-align: center;
    }
    .layui-table td[data-field="6"]{
        text-align: left;
    }
    .layui-badge{
        height: 19px;
        line-height: 21px;
        border-radius: 9px;
        padding: 0 16px;
    }
    .left-card{
        margin-bottom: 0;
    }
    .layui-card-header{
        height: 19px;
        line-height: normal;
        padding: 10px;
        background-color: #F6F7F8;
    }
    .layui-card-body{
        padding: 0;
    }
    .card-header-icon{
        width: 18px;
        height: 18px;
    }
    .card-header-title{
        margin-left: 10px;
    }
    .layui-table-view .layui-table th, .layui-table-view .layui-table td{
        padding: 4px 0;
    }
    .btn-submit, .btn-forward, .btn-detail, .btn-assign, .btn-return{
        height: 22px;
        font-size: 12px;
        border-radius: 4px;
    }
    .btn-submit{
        width: 48px;
        border: 1px solid #4BAA0B;
        color: #4BAA0B;
    }
    .btn-forward{
        width: 48px;
        border: 1px solid #1C74D4;
        color: #1C74D4;
    }
    .btn-detail {
        border: 1px solid #1C74D4;
        color: #1C74D4;
    }
    .btn-assign{
        width: 60px;
        border: 1px solid #0078FF;
        color: #0078FF;
    }
    .btn-return{
        width: 62px;
        border: 1px solid #828282;
        color: #828282;
    }
    .layui-btn+.layui-btn{
        margin-left: 0;
    }
    .layui-fluid{
        padding: 0 15px 0 15px;
    }
    .task-content-box{
        float: left;
        width: 70%;
        height: 32px;
        text-overflow: ellipsis;
        overflow: hidden;
    }
    .task-num{
        display: inline-block;
        width: 25px;
        font-size: 16px;
        color: #373737;
        font-weight:bold;
    }
    .task-content{
        color: #373737;
    }
    .task-time{
        float: right;
        width: 30%;
        height: 32px;
        color: #666666;
        overflow: hidden;
        text-align: right;
    }

    /*填报表单详情*/
    .select-form-header{
        position: relative;
    }
    .card-header-right{
        position: absolute;
        right: 0;
        top: 0;
    }
    .layui-card .layui-tab{
        margin-top: 13px;
        z-index: 9999;
    }
    .layui-tab-card>.layui-tab-title{
        background: #fff;
    }
    .layui-tab-card{
        border-top: none;
    }
    .select-form-box{
        min-height: 400px;
    }
    .btn-export, .btn-import, .btn-saveform, .btn-subform{
        width: 96px;
        height: 30px;
        line-height: 30px;
        border: 1px solid #2669B1;
        font-weight:600;
        font-size: 14px;
        padding-left: 31px;
        color: #FFFFFF;
        cursor: pointer;
    }
    .btn-subform{
        margin-right: 14px;
        background: url(../../../../dist/style/res/formFill/form-submit.png) no-repeat #2669B1;
        background-position: 7px 5px;
    }
    .btn-saveform{
        margin-right: 14px;
        background: url(../../../../dist/style/res/formFill/saveForm.png) no-repeat #2669B1;
        background-position: 7px 5px;
    }
    .btn-export{
        margin-right: 14px;
        background: url(../../../../dist/style/res/formFill/export.png) no-repeat #2669B1;
        background-position: 7px 7px;
    }
    .btn-import{
        background: url(../../../../dist/style/res/formFill/import.png) no-repeat #2669B1;
        background-position: 10px 6px;
    }
    .layui-tab-content{
        text-align: center;
    }
    .layui-table tbody tr.bgRed{
        background: red;
    }
    #test-table-cellEdit{
        width: 100%;
        text-align: center;
    }
    .layui-table-box .layui-table[lay-even] tbody tr.lineactive{
        background-color: #FDE7A3;
    }
    .left-card .layui-table-cell{
       height: inherit;
       text-align: center;
    }
    .btn-colla{
        height: 30px;
        line-height: 30px;
        border: none;
    }
    .btn-colla .layui-icon{
        right: 7px;
    }
    /* .kqform-content {
        overflow: auto;
    } */
    .layui-layer-page .layui-layer-content{
        overflow: hidden;
    }
    #usermemo{
        overflow: hidden;
    }
    #usermemo .layui-form-label{
        width: auto;
        padding:  9px 10px;
    }
    .layui-layer-btn .layui-layer-btn0{
        background-color: #2669B1;
        border-color: #2669B1;
    }
    .kq-info-title {
        display: inline-block;
        height: 30px;
        line-height: 30px;
        margin-right: 30px;
    }
    .my-table-btn-del, .my-table-btn-add, .my-table-btn-check{
        font-size: 20px;
		border-width: 1px;
		border-style: solid;
		border-radius: 4px;
	}
    .my-table-btn-del{
        color: #FF4E32 !important;
		border-color: #FF4E32;
    }
    .my-table-btn-add{
        color: #2EB36C !important;
		border-color: #2EB36C;
    }
    .my-table-btn-check{
        color: #FF4E32 !important;
		border-color: #FF4E32;
    }
	.my-table-btn-del:hover, .my-table-btn-add:hover, .my-table-btn-check:hover{
		color: #0BAFFD !important;
		border-color: #0BAFFD;
	}
    .left-card .no-data-tips{
        margin-top: 70px;
    }
    .task-ul .no-data-tips{
        margin-top: 100px;
    }
    .layui-tab-content .layui-table th{
        border: 1px solid #e6e6ee;
    }
    .layui-tab-content th, .layui-tab-content td{
        text-align: center !important;
    }
    .height-auto{
        height: 385px;
    }
    .height-max{
        height: 825px;
    }
    .download-fileBox{
        position: relative;
    }
    .fileAllBox{
        position: absolute;
        left: 14%;
        top: 26px;
        background: #000;
        display: none;
        padding: 6px;
        z-index: 9999;
    }
    .fileAllBox p{
        color: white;
        font-size: 14px;
    }
    .showEntuserCircle{
        display: inline-block;
        width: 10px;
        height: 10px;
        position: absolute;
        background: #ef5757;
        border-radius: 50%;
        top: 35%;
        right: 6px;
        cursor: pointer;
    }
</style>

<!-- 填报表单工具栏 -->
<script type="text/html" id="modify-form">
    <a class="layui-icon layui-icon-add-1 my-table-btn-add" lay-event="addLine" lay-tips="新增"></a>
    <a class="layui-icon layui-icon-delete my-table-btn-del" lay-event="delLine" lay-tips="删除"></a>
    {{# if(d.model != 'insert'){ }}
        <a class="layui-icon layui-icon-form my-table-btn-check" lay-event="check" lay-tips="查看记录"></a>
    {{# } }}
</script>

<!-- 任务列表状态栏 -->
<script type="text/html" id="state">
    {{#
		var getStatusColor = function() {
			var mapColors = {
                '00': 'layui-bk-green',
                '20': 'layui-bk-gray',
                '25': 'layui-bk-orange',
                '30': 'layui-bk-green',
                '40': 'layui-bk-orange',
                '90': 'layui-bk-gray',
                '99': 'layui-bk-gray'
			};
			return mapColors[d.state] || '';
        };
        var disPlayTxt=d.entuser_name?'inline-block':'none' 
	}}
    <!-- <span class="custom-badge {{getStatusColor()}}">{{d.statename}}</span> -->
    <div class="custom-badge {{getStatusColor()}}">{{d.statename}}<span  class="showEntuserCircle" style="display:{{disPlayTxt}}" lay-tips='委托人：{{d.entuser_name}}'></span></div>		
</script>

<!-- 任务列表操作栏 -->
<script type="text/html" id="test-table-thead-barDemo">
        <a class="layui-btn layui-btn-primary layui-btn-xs btn-detail layui-hide" lay-event="detail"><span>下发单位</span></a>
        {{# if(d.writetype != '3'){ }}
            <a class="layui-btn layui-btn-primary layui-btn-xs btn-forward" lay-event="forward">
                {{# if(d.zf){ }}
                    <span>已转发</span>
                {{# }else{ }}
                    <span>转发</span>
                {{# } }}
            </a>
            <a class="layui-btn layui-btn-primary layui-btn-xs btn-assign" lay-event="assign">
                {{# if(d.fp){ }}
                    <span>已分配</span>
                {{# }else{ }}
                    <span>分配任务</span>
                {{# } }}
            </a>
        {{# } }}
</script>
            
<!-- 任务列表附件栏 -->
<script id="download" type="text/html">
    {{# if(!!d.fileNames && d.fileNames.length && d.fileNames.length > 0){     }}
        {{#   layui.each(d.fileNames, function(index, file){ }} 
            <a class="download-file" lay-event="download" data-url={{file.url}} lay-tips='{{file.filename}}'>{{file.filename}}</a>
        {{# }); }}  
    {{# } }}
</script>
<!-- 待办任务 -->
<script type="text/html" id="auditTask">
    {{# if(d && d.length > 0){ }}
        <li class="undotask-header">
            <span class="title-num">序号</span>
            <span class="title-content">任务名称</span>
            <span class="title-time">填报结束时间</span>
        </li>
        {{# layui.each(d, function(index, item){ }}
            <li class="clearfix T-btn" data-jump={{item.connection}} data-target="jump">
                <div class="task-content-box">
                    <span class="task-num">{{index+1}}</span>
                    <span class="task-content" lay-tips={{item.taskname}}>{{item.statename}}-{{item.taskname}}</span>
                </div>
                <div class="task-time">{{item.endtime}}</div>
            </li>
        {{# }) }}
    {{# }else { }}
        <div class="no-data-tips">
            <img src="/src/style/res/about/empty.png">
            <p style="color:#DBDBDB;">暂无数据</p>
        </div>
    {{# } }}
</script>
<!-- 日期时间 -->
<script type="text/html" id="datetime">
    <input type="text" name="approvalTime" class="layui-input layui-input-date">
</script>
 <!-- 单位单选框 -->
<script type="text/html" id="unitRadios">
    {{#  if(d && d.length > 0){ }}
        {{# layui.each(d, function(index, item){ }}
            <input type="radio" name="dept" value="{{item.dept_id}}" title="{{item.dept_name}}" lay-filter="custom-unit-radio" {{item.checked ? "checked" : ""}} />
        {{# }) }}
    {{#  } }}
</script>
<script>
layui.use(['admin', 'table', 'element', 'tools', 'upload', 'laytpl', 'laydate', 'form'], function(){
    var table = layui.table,
        element = layui.element,
        $ = layui.jquery,
        admin = layui.admin,
        tools = layui.tools,
        view = layui.view,
        upload = layui.upload,
        laytpl = layui.laytpl,
        router = layui.router(),
        search = router.search,
        laydate = layui.laydate,
        form = layui.form,
        router = layui.router();

    var colName = [], //列名
        tablename = [], //当前表单名
        formtId = [],
        selectData = [],
        allCols = [],
        delRows = [],
        FormData = []; //表单信息
        window.tabIndex = 0; //选项卡下标 默认为0
        window.tableId = 'test-table-cellEdit1', //选项卡表单id
        layout = ['.layui-table th', '.layui-table td', '.task-ul>ul', '#fill-form-kqform', '.kq-info-title'],
        clickFresh=false;//是否点击刷新按钮

    // tools.initCite(router, {kqfirstMenu: '考勤管理', kqsecondMenu: '考勤填报'}, {czfirstMenu: '考勤管理', czsecondMenu: '考勤填报'}); //加载breadcurmb
    getTaskTable(); //任务列表加载
    //getUndoTask(); //待办任务加载
    getKqSelect(); //获取考勤状态下拉选项数据
    addToolListen(); //监听工具栏
    changeTab(); //监听tab切换

    //填报考勤任务表单详情列表加载
    function getKQTaskForm(taskid, writeid, callback) {
        admin.req({
            // url: 'myapi/DC/api/rest/web/custom/CheckTaskGetWriteData',
            url: 'myapi/DC/api/rest/web/custom/CheckWrite',
            data: {
                taskid: taskid,
                writeid: writeid,
                checking: '1',
            },
            success: function(res) {  
                if(res.retcode == '0'){
                    // var data = res.data.data.data,
                    var data = res.data.data,
                        dates = data.users.length > 0 ? data.users[0].users_time[0].users_time_day : [],
                        users = data.users;
                    $('.kq-info-title .c-startDate').text(data.starttime ||' 暂无');
                    $('.kq-info-title .c-endDate').text(data.endtime ||' 暂无');
                    view('fill-form-kqform').render('./fill/components/kqTable', {
                        dates: dates, 
                        users: users, 
                        options: selectData,
                        basic: {
                            dept_code: data.dept_code,
                            dept_name: data.dept_name,
                            dept_id: data.dept_id,
                            taskid: taskid
                        }
                    }).done(function(res){ 
                        if(users&&users.length==0){ 
                            $(".formFillKqTableBox1 table").empty(); 
                        }   
                    }) 
                    callback && callback(res);

                }
            }
        });
    }

    //填报表单详情列表加载
    function getTaskForm(taskid, writeid, link, deptId, checking, getCols, dv_results){ 
        tablename = [];
        formtId = [];
        allCols = [];
        getCols = getCols ? getCols : '';
        dv_results = dv_results ? dv_results: {};
        var deptId = deptId ? deptId : '';
        admin.req({
            type: 'post',
            url: 'myapi/DC/api/rest/web/custom/GetFormsByWriteTask',
            data: {
                id: taskid,
                writeid: writeid,
                link: link,
                checking: checking || '',
                dept_id: deptId
            },
            success: function(res) {
                if(res.retcode == '0' && res.data && res.data.length > 0){
                    FormData = res.data;
                    setUnitRadios(FormData[0], deptId);
                    $('#'+window.tableId).empty();
                    var titleHtml = '',
                        tableHtml = '';
                    for(var i = 0; i < res.data.length; i++){
                        if(i == window.tabIndex){ 
                            titleHtml +=  '<li class="layui-this">'+res.data[i].formname+'</li>';
                            tableHtml += '<div class="layui-tab-item layui-show" id='+res.data[i].id+'>'+
                                            '<table id="test-table-cellEdit'+(i+1)+'" lay-filter="test-table-cellEdit'+(i+1)+'"></table>'+
                                         '</div>';
                        }
                        else{ 
                            titleHtml += ' <li>'+res.data[i].formname+'</li>';
                            tableHtml += '<div class="layui-tab-item" id='+res.data[i].id+'>'+
                                            '<table id="test-table-cellEdit'+(i+1)+'" lay-filter="test-table-cellEdit'+(i+1)+'"></table>'+
                                         '</div>';
                        }
                    }
                    $('.form-tab-title').empty().html(titleHtml);
                    $('.form-tab-content').empty().html(tableHtml);
                    layui.each(res.data, function(index, item){
                        var field = item.form_field,
                            cols = item.cols,
                            tbody = item.data.grid,
                            colsss = [],
                            colData = [],
                            fieldRole = item.fieldRole,
                            warnResults = item.dv_results,
                            finalCols = [],
                            supContent = item.supcontent;
                            obj = new Object(),
                            selfId = item.id,
                            maxRow  = 1;	

                        tablename.push(item.tablename);
                        formtId.push(item.formt_id);
                        //得到数据标题行
                        $.each(field,function(index, item) {
                            $.each(fieldRole, function(i, role){
                                if(item.fieldenglish === role.fieldenglish){
                                    item.see = role.see;
                                    item.edit = role.edit;
                                }
                            });
                            colName.push(item.fieldenglish);
                            if(item.datatype != 'date'){
                                if(item.see != '0'){ 
                                    var param = {
                                        field: item.fieldenglish,
                                        title: item.fieldname,
                                        minWidth: 230
                                    };
                                    param.event = item.edit && item.edit == '0' ? 'mustFill' : [item.nonull, item.datatype];
                                    item.edit && item.edit == '0' ?  '' : param.edit = 'text';
                                    finalCols.push(param);
                                }
                            }else{
                                if(item.see != '0'){ 
                                    finalCols.push({
                                        field: item.fieldenglish,
                                        title: item.fieldname,
                                        minWidth: 230,
                                        event: [item.nonull, item.datatype],
                                        templet: '#datetime'
                                    });
                                }
                            }
                        });
                        colsss = tools.handleCols(cols, finalCols);	
                        tools.addOtherCols(colsss);	 							
                        if(tbody.length > 0){ 
                            colData = tbody;
                            layui.each(colData, function(index, item){
                                item.model = 'normal';
                                item.tableId = selfId;
                            });
                        }else{ //无内容默认加载maxRow个空行
                            for(var i = 0; i < maxRow; i++){
                                var blankLine = {};
                                for(var j = 0; j < colName.length; j++){
                                    blankLine[colName[j]] = "";
                                    blankLine.model = "insert";
                                    blankLine.id = createUniqueId(1);
                                    blankLine.tableId = selfId;
                                }
                                colData.push(blankLine);
                            }
                        }															
                        if(getCols){
                            allCols.push(colsss);
                            tools.handleWarnInfo(colsss, dv_results);
                        }else{
                            tools.handleWarnInfo(colsss, warnResults);
                        }
                        var options = {
                            elem: '#test-table-cellEdit'+(index+1)
                            ,cols: colsss
                            ,text: {
                                none: '<div class="no-data-tips"><img src="/src/style/res/about/empty.png"><p style="color:#DBDBDB;">暂无数据</p></div>'
                            }
                            ,skin: 'nob'
                            ,height: 250
                            ,even: true
                            ,limit: 5000
                            ,data: colData
                            ,done: function(res, curr, index){
                                var data = res.data;
                                supContent = tools.handleSelectVal(supContent, tbody, data[0].tableId);
                                tools.loadSelectFunction(supContent);
                                //加载下拉选值框
                                var tableId = data[0].tableId,
                                    selectDiv = $('#'+tableId+' td[lay-event]');
                                $.each(selectDiv, function(k, each){
                                    var tr = $(this).parents('tr').index(),
                                        event = $(this).attr('lay-event').split(',')[1];
                                    if(event && event == 'select'){
                                        var field = $(this).data('field'),
                                            selectVal = data[tr][field] || '';
                                        $(this).find('select').val(selectVal)
                                    }
                                });
                                //加载日期选择框
                                $('.layui-input-date').each(function(index, item){
                                    var field = $(this).parents('td').data('field'),
                                        datatime = '';
                                    if(data[index][field]){
                                        datatime = $.trim(data[index][field]);
                                    }
                                    laydate.render({
                                        elem: this,
                                        type: 'date',
                                        format: 'yyyy-MM-dd',
                                        isInitValue: true, 
                                        value: datatime, 
                                        trigger: 'click'
                                    })
                                });
                                form.render('select', 'custom-tabSwitch');
                            }
                        }
                        table.render(options);
                    })
                }else{
                    $('.form-tab-title').empty();
                    $('#'+window.tableId).next().find('.layui-table-box').empty();
                }
            }
        })
    }

    //任务列表
    function getTaskTable(){
        var cols = [
            { type: 'numbers', title: '序号', width: 44 },
                { title: '任务状态', toolbar: '#state', width: 105 },
                {
                    field:'taskname',
                    title: '任务名称', 
                    width: 300,
                    templet: function(d){
                        return '<span lay-tips="'+ d.taskname +'">'+ d.taskname +'</span>'
                    }
                }
                ,{field:'starttime', title: '开始时间', width: 220, 
                    templet: function(d){
                        return '<span lay-tips="'+ d.starttime +'">'+ d.starttime +'</span>'
                    }
                }
                ,{field:'endtime', title: '结束时间', width: 220, 
                    templet: function(d){
                        return '<span lay-tips="'+ d.endtime +'">'+ d.endtime +'</span>'
                    }
                }
                ,{
                    field:'memo', 
                    title: '填报要求',
                    width: 220,
                    templet: function(d){
                        return '<span lay-tips="'+ d.memo +'">'+ d.memo +'</span>'
                    }
                }
                ,{ field: 'username', title: '发布人', width: 150, templet: function(d){
                        return '<span lay-tips="'+ d.username +'">'+ d.username +'</span>'
                    } 
                }
                ,{ field: 'deptname', title: '任务发布单位', width: 150,
                    templet: function(d){
                        return '<span lay-tips="'+ d.deptname +'">'+ d.deptname +'</span>'
                    }
                }
                ,{field: 'createtime', title: '发布时间', width: 220, 
                    templet: function(d){
                        return '<span lay-tips="'+ d.createtime +'">'+ d.createtime +'</span>'
                    }
                }
                ,{ title: '任务附件',  width:200,
                // toolbar: '#download',
                    field:'fileNames',
                    templet: function(d){  
                        var newDownLoadBox="";
                        var fileNames=d.fileNames;
                        if(fileNames&&fileNames.length>0){
                            for(var i=0;i<fileNames.length;i++){
                                newDownLoadBox+='<p class="download-file" lay-event="download" data-url='+fileNames[i].url+' >'+fileNames[i].filename+'</p>'
                            }   
                            return ' <div class="download-fileBox">'+
                                    '<a class="download-file downLoadFileBtn" taskid='+d.taskid+' >下载附件</a>'+  
                                    '<div class="fileAllBox">'+
                                        newDownLoadBox+
                                    '</div>'+
                                    '</div>'
                            
                        }else{
                            return '' 
                        }
                        // <a class="download-file" lay-event="download" data-url={{file.url}} lay-tips='{{file.filename}}'>{{file.filename}}</a>
                        }  
                    }  
                ,{ field: 'opearte', title:'任务操作', toolbar: '#test-table-thead-barDemo', width: 210 }
            ];
        table.render({
            elem: '#test-table-simple1'
            ,height: 385
            ,url: 'myapi/DC/api/rest/web/custom/TaskBacklog'
            ,where: {
                type:'write',
                access_token: layui.data('layuiAdmin').access_token,
                jsonId: layui.data('layuiAdmin').access_token
            }
            ,request: {
                limitName: 'count'
            }
            ,parseData: function(res){   
                var data = res.data.data,
                    newdata = [];
                layui.each(data, function(index, item){
                    item.writetype == '3' && newdata.push(item);
                });  
                if(!clickFresh){
                    data.length == newdata.length && cols.pop();
                } 
                return {
                    "code": res.retcode, 
                    "msg": res.retmsg, 
                    "count": res.data.totalNumber, 
                    "data": data
                }
            }
            ,cellMinWidth: 80 
            ,page: {
                groups: 1, 
                limit: 10,
                next:'<i class="layui-icon">&#xe602;</i>',
                prev:'<i class="layui-icon">&#xe603;</i>',
                first: '<i class="layui-icon">&#xe65a;</i>',
                last: '<i class="layui-icon">&#xe65b;</i>',
                layout: ['refresh', 'first', 'prev', 'skip', 'count','allPage', 'next', 'last'],
                extend:{
                    first: true, //是否显示首页
                    spr: false,//是否显示页码分页符号 默认显示
                    pagecount: true//页码是否显示总数  groups=1时才有效
                }
            }
            ,cols: [cols]
            ,even: true 
            ,initSort: {
                field: 'starttime',
                type: 'asc'
            }
            ,done: function(res, curr, count){ 
                if(res.data && count > 0){  
                    window.taskId = res.data[0].taskid;
                    window.writeId = res.data[0].writeid; //默认保存第一条任务的writeid和taskid 、link
                    window.link = res.data[0].link;
                    window.review = res.data[0].review;  
                    tools.clickToTask(table.cache['test-table-simple1'], router, 'test-table-simple1');   
                    $(".download-fileBox").parent(".layui-table-cell").css({"overflow":"visible"})
                    $(".download-fileBox").on("mouseover",function(){  
                        $(this).find(".fileAllBox").show();  
                    })
                    $(".download-fileBox").on("mouseout",function(){ 
                        $(this).find(".fileAllBox").hide(); 
                    })
                    $(".downLoadFileBtn").on('click',function(){
                        tools.downLoadMutipleFileFun($(this).attr("taskid")) 
                     })
                    if(res.data[0].checking === '1') {//考勤任务
                        window.checking = '1';
                        //getKQTaskForm(res.data[0].taskid, res.data[0].writeid); 
                        $('.kq-info-title .c-unit').text(res.data[0].deptname ||' 暂无');
                        pickTypeShow('kqform');
                    }else {
                        //getTaskForm(res.data[0].taskid, res.data[0].writeid, res.data[0].link); //默认加载第一项任务的所有表单
                        pickTypeShow('other');
                    } 
                }
                tools.setFont(layout);
                 //监听刷新按钮点击 
                 $(".layui-laypage-refresh .layui-icon").on("click",function(){   
                     clickFresh=true;
                }) 
                clickFresh=false;
            }
        }); 
    }

    //不同任务类型做不同的元素切换
    function pickTypeShow(type) {
        if(type === 'other') {
            $('.card-header-kq').hide();
            $('.kqform-content').hide();
            $('.card-header-other').show();
            $('.otherForm-content').show();
        }else if(type === 'kqform') {
            $('.card-header-other').hide();
            $('.otherForm-content').hide();
            $('.card-header-kq').show();
            $('.kqform-content').show();
        }
    }

    //待办任务
    function getUndoTask(){
        admin.req({
            url: 'myapi/DC/api/rest/web/custom/GetTasksByUserApp',
            data: {
                app_id: layui.data('userdata').appId,
            },
            success: function(res){
                if(res.retcode == '0'){
                    var data = res.data.auditTask.concat(res.data.writeTask),
                        getTpl = auditTask.innerHTML,
                        view = document.querySelector('.task-ul ul');
                    laytpl(getTpl).render(data, function(html){
                        view.innerHTML = html;
                    })
                }
            }
        });
    }

    //设置填报表单单位单选框
    function setUnitRadios(data, checkId){
        var deptMsgs = data.deptMsgs || [],
            view = document.getElementById('dept'),
            getTpl = unitRadios.innerHTML;
        if(deptMsgs && deptMsgs.length > 0){
            deptMsgs && deptMsgs[0].dept_name != '全部' ? deptMsgs.unshift({dept_name: '全部', dept_id: ''}) : '';
            layui.each(deptMsgs, function(index, item){
                item.checked = false;
                item.dept_id == checkId ? item.checked = true : ''
            });
        }
        laytpl(getTpl).render(deptMsgs, function(html){
            view.innerHTML = html;
        });
        form.render('radio', 'custom-tabSwitch');
    }

    //获取考勤状态下拉选项数据
    function getKqSelect() {
        admin.req({
            type: 'get',
            url: 'myapi/DC/api/rest/web/custom/CheckworkSymbolSelect',
            success: function(res) {
                selectData = res.data && res.data.length ? res.data : [];
            }
        });
    }

    //监听Tab切换
    element.on('tab(custom-tabSwitch)', function(data){
        var index = data.index + 1;
        window.tableId = 'test-table-cellEdit'+index; //表格ID
        window.tabIndex = data.index; //选项卡下标
        // $('#btn-import').attr('data-id', FormData[window.tabIndex].formt_id);
        // $('#btn-import').attr('data-taskid', FormData[window.tabIndex].taskid);
        addToolListen(); 
        changeTab();
        setUnitRadios(FormData[data.index], '');
    });

    //任务列表 => 监听行点击事件
    table.on('row(test-table-simple1)', function(obj){
        $('[lay-id="test-table-simple1"]').find(obj.tr.selector).addClass('lineactive');
        $('[lay-id="test-table-simple1"]').find(obj.tr.selector).siblings().removeClass('lineactive');
        window.taskId = obj.data.taskid;
        window.writeId = obj.data.writeid;
        window.link = obj.data.link;
        window.review = obj.data.review;
        window.checking = obj.data.checking;
        tools.setNavText();
        tools.setTaskFormTitle(obj.data.taskname);
        if(checking === '1') {
            getKQTaskForm(obj.data.taskid, obj.data.writeid);
            $('.kq-info-title .c-unit').text(obj.data.deptname ||' 暂无');
            pickTypeShow('kqform');
        }else {
            window.tabIndex = 0;
            window.tableId = 'test-table-cellEdit1'; //默认第一个表格加载
            getTaskForm(obj.data.taskid, obj.data.writeid, obj.data.link);
            pickTypeShow('other');
        }
    });

    //监听表格复选框复选
    table.on('checkbox('+window.tableId+')', function(obj){
        var type = obj.type,
            checked = obj.checked,
            tr = obj.tr;
        if(type == 'one' && !checked){
            var tds = tr[0].childNodes;
            layui.each(tds, function(index, item){
                $(this).attr('style') && $(this).removeAttr('style');
            });
        }
    });
    //监听单位单选框单选
    form.on('radio(custom-unit-radio)', function(data){
        getTaskForm(window.taskId, window.writeId, window.link, data.value);
    });
   
    //任务列表表格 =>监听操作栏事件
    table.on('tool(test-table-simple1)', function(obj){
        layui.stope(obj.ev); //阻止事件冒泡
        if(obj.event == 'forward'){ 
            var taskid = obj.data.taskid,
                writeid = obj.data.writeid,
                text = $(this).find('span').text();
                forwardUnit = [],
                forwardGrp = [],
                that = this;
            admin.req({
                url: 'myapi/DC/api/rest/web/custom/getWriteUserAndForm',
                data: {
                    taskid: taskid,
                    writeid: obj.data.writeid,
                    link: obj.data.link,
                    jsonId: layui.data('layuiAdmin').access_token
                },
                success: function(res){
                    if(res.retcode == 0){
                        var index = layer.open({
                            id: 'formFill-transmithtml',
                            title: '<i class="formFill-icon"></i><span style="color:#FFF;">转发任务</span>',
                            offset: '100px',
                            type: 1,
                            shadeClose: true,
                            resize: false,
                            area: ['1133px', '659px'],
                            success: function(lay, index){
                                var data = {
                                    taskid: obj.data.taskid,
                                    access_token: layui.data('layuiAdmin').access_token,
                                    jsonId: layui.data('layuiAdmin').access_token,
                                    writeid: obj.data.writeid,
                                    index: index,
                                    deptMsg: res.data.deptMsg,  
                                    groupMsg: res.data.groupMsg,
                                    formMsg: res.data.formMsg,
                                    wadduserMsg: res.data.wadduserMsg,
                                    link: obj.data.link,
                                    transmitState: text,
                                    zf: JSON.stringify(obj.data.zf)
                                }; 
                                view(this.id).render('./fill/transmit', data).done(function(){
                                    $(lay).on('click', '.lay-submit', function(){
                                        $(that).find('span').text('已转发');
                                    })
                                });
                            }
                        })
                    }
                }
            })
    }else if(obj.event == 'assign'){
        var belTo = obj.data.writeid,
            taskid = obj.data.taskid,
            review = obj.data.review,
            text = $(this).find('span').text(),
            that = this;
        admin.req({
            url: 'myapi/DC/api/rest/web/custom/GetAllotUser',
            data: {
                taskid: taskid,
                writeid: obj.data.writeid,
                jsonId: layui.data('layuiAdmin').access_token
            },
            success: function(res){
                if(res.retcode == 0){
                    var index = layer.open({
                        id: 'formFill-assignhtml',
                        title: '<i class="formFill-icon"></i><span style="color:#FFF;">分配任务</span>',
                        offset: '20px',
                        type: 1,
                        resize: false,
                        shadeClose: true,
                        area: ['600px', '650px'],
                        success: function(lay, index){
                            var preMsg = res.data != '无数据' ? tools.removeSamePerson(res.data) : [];
                            view(this.id).render('./fill/transmitDep/self', {
                                persentMsg: preMsg,
                                assignState: text
                            }).done(function(){ 
                                var preName = [];
                                if(preMsg && preMsg.length > 0){
                                    layui.each(preMsg, function(index, item){
                                        preName.push(item.writeusername);
                                    });
                                }
                                $(lay).on('click', '.T-confirm', function(){
                                    preMsg = res.data != '无数据' ? tools.removeSamePerson(res.data) : [];
                                    var checkName = [],
                                        checkAllName = [],
                                        checkAllData = [],
                                        options = [];
                                    var units = $(lay).find('#assignName .unit-content');
                                    layui.each(units, function(index, item){
                                        var usercode = $(this).data('usercode'),
                                            certcode = $(this).data('certcode'),
                                            name = $(this).data('name'),
                                            deptcode = $(this).data('deptcode'),
                                            deptname = $(this).data('deptname'),
                                            deptid = $(this).data('deptid');
                                        checkName.push(name);
                                        checkAllData.push({ user_code: usercode, cert_code: certcode, name: name, dept_code: deptcode, dept_name: deptname, dept_id: deptid })
                                    });
                                    checkAllName = checkName.concat(preName); 
                                    checkAllData = checkAllData.concat(preMsg); 
                                    var addName = [], //新增的名字
                                        delName = []; //删除的名字
                                        normalName = []; //普通状态
                                    for(var i = 0; i < checkName.length; i++){
                                        preName.indexOf(checkName[i]) == -1 ? addName.push(checkName[i]) :  normalName.push(checkName[i]);
                                    }
                                    var exceptDel = addName.concat(normalName);
                                    layui.each(checkAllName, function(index, item){
                                        if(exceptDel.indexOf(item) == -1){
                                            delName.push(item);
                                        }
                                    });
                                    layui.each(checkAllData, function(index3, item3){
                                        !item3.name ? item3.name = item3.username : '';
                                        var obj = {
                                            writeid: belTo,
                                            review: review,
                                            dataid: item3.user_code,
                                            writeuserid: item3.cert_code,
                                            writeusername: item3.name,
                                            dept_code: item3.dept_code,
                                            dept_name: item3.dept_name,
                                            dept_id: item3.dept_id,
                                            access_token: layui.data('layuiAdmin').access_token,
                                            jsonId: layui.data('layuiAdmin').access_token
                                        };
                                        if(addName.length > 0){
                                            for(var i = 0; i < addName.length; i++){
                                                item3.name == addName[i] ? obj.model = 'add' : '';
                                            }
                                        }
                                        if(delName.length > 0){
                                            for(var i = 0; i < delName.length; i++){
                                                item3.name == delName[i] ? obj.model = 'del' : '';
                                            }
                                        }
                                        if(normalName.length > 0){
                                            for(var i = 0; i < normalName.length; i++){
                                                item3.name == normalName[i] && item3.user_code ?  obj.model = 'normal' : '';
                                            }
                                        }
                                        options.push(obj);
                                    });
                                    if(options && options.length <= 0){
                                        layer.msg('请选择人员', {time: 1500});
                                        return ;
                                    }
                                    admin.req({
                                        url: 'myapi/DC/api/rest/web/custom/saveUnitPersonnel',
                                        data: {
                                            taskid: obj.data.taskid,
                                            jsonId: layui.data('layuiAdmin').access_token,
                                            persentMsg: JSON.stringify(options),
                                            link: obj.data.link
                                        },
                                        success: function(res){
                                            if(res.retcode == 0){
                                                $(that).find('span').text('已分配');
                                                layer.msg(res.retmsg, {time: 1500});
                                            }
                                        }
                                    })
                            		layer.close(index);
                                })
                            })
                        }
                    })

                }
            }
        })
    }else if(obj.event == 'download'){
        var url = 'myapi/DC/'+ $(this).data('url'),
			name = $(this).text();
		tools.downMethodfunction(url, name);    
    }else if(obj.event === 'detail') {
        var detail = obj.data;
        if(detail.tasktype === 'ls') {
            admin.req({
                url: 'myapi/DC/api/rest/web/custom/DCWriteGetTaskMsgsById',
                data: {
                    id: detail.taskid
                },
                success: function(res){
                    if(res.retcode == '0'){
                        layer.open({
                            id: 'temporary-viewHtml',
                            title: '<i class="formFill-icon"></i><span style="color:#FFF;">查看临时任务</span>',
                            offset: '20px',
                            type: 1,
                            resize: false,
                            shadeClose: true,
                            area: ['1133px', '380px'],
                            success: function(lay) {
                                var passData = res.data;
                                view(this.id).render('./task/temporary/view', passData);
                            }
                        });
                    }
                }
            })
        }else if(detail.tasktype === 'cz') {
            var checking = detail.checking;
            var url = checking !== '1' ? 'myapi/DC/api/rest/web/custom/DCWriteGetTaskMsgsById' : 'myapi/DC/api/rest/web/custom/CheckTaskDataSelect?model=updateSelect';
            var args = {
                id: detail.taskid
            },
            cArgs = {
                taskid: detail.taskid
            };
            admin.req({
                url: url,
                data: checking !== '1' ? args : cArgs,
                success: function(res){
                    var data = checking !== '1' ? res.data : res.data.data;
                    layer.open({
                        id: checking !== '1' ? 'permanent-viewhtml' : 'attence-viewhtml',
                        title: checking !== '1' ? '查看常驻任务' : '查看考勤任务',
                        offset: '20px',
                        type: 1,
                        resize: false,
                        shadeClose: true,
                        area: checking !== '1' ? ['1133px', '400px'] : ['1133px', '350px'],
                        success: function(lay) {
                            var timeDate = data.timeDate && data.timeDate.length && data.timeDate.length > 0 ? data.timeDate : [];
                            var settype = data.timeDate.length > 0 ? data.timeDate[0].settype : '0';
                            var hz = data.timeDate.length > 0 ? data.timeDate[0].hz : 'year';
                            data.settype = settype;
                            data.hz = hz;
                            var temUrl = checking !== '1' ? './fill/components/czView' : './task/permanent/attenceView';
                            view(this.id).render(temUrl,data);
                        }
                    });
                }
            });
        }
    }
  }) 


    function getFormMsg(formHtml, baseName, baseId, choose){
            if (formHtml) {
                var template = document.createElement('div');
                template.innerHTML = formHtml;
                var tableTitle = template.querySelector('caption'); 
                if (tableTitle) {
                    var tablename = template.querySelector('caption').innerText, 
                        formId = template.querySelector('table').getAttribute('id'); 
                    if (tablename) {
                        var ths = template.querySelectorAll('.firstRow th');
                        var property = new Object();
                        var grid = [];
                        var thnewName = [];
                        if (ths.length > 0) {
                            for (var i = 0; i < ths.length; i++) {
                                var obj = new Object();
                                obj.form_typeid = formId; //字段所属表格或表单id
                                obj.fieldstate = '1'; //字段状态  正常使用为1,被删除为0
                                var text = ths[i].innerText; //字段中文名称
                                thnewName.push(text);
                                var colId = ths[i].getAttribute('id'); //字段英文名称
                                if (text) obj.fieldname = text;
                                if (colId) obj.fieldenglish = colId;
                                var sort = ths[i].getAttribute('table_sort');
                                var query = ths[i].getAttribute('query');
                                var sum = ths[i].getAttribute('sum');
                                var average = ths[i].getAttribute('average');
                                var count = ths[i].getAttribute('count');
                                var colSum = ths[i].getAttribute('col_sum');
                                var colAverage = ths[i].getAttribute('col_average');
                                var colCount = ths[i].getAttribute('col_count');
                                var dataType = ths[i].getAttribute('data_type'); //字段类型
                                var dataLength = ths[i].getAttribute('data_length'); //字段长度
                                var isFill = ths[i].getAttribute('isfill'); //必填
                                var thModel = ths[i].getAttribute('model'); //内层model属性
                                if (sort) obj.sortno = sort //排序
                                else {obj.sortno = 'null'};
                                if (dataLength) obj.length = dataLength; //字段长度
                                if (query) obj.queryno = query; //查询
                                if (average == '1' || sum == '1' || count == '1' || colSum ==
                                    '1' || colAverage == '1' || colCount == '1') obj.stacno =
                                    '1';
                                else obj.stacno = '0';
                                if (dataType) obj.datatype = dataType;
                                if (isFill) obj.nonull = isFill;
                                if(thModel) obj.model = thModel;
                                grid.push(obj);
                            }
                        }

                        var tableModel = template.querySelector('table').getAttribute('model'); 
                        property.formname = tablename;
                        property.html = formHtml;
                        if(choose){
                            property.model = choose;
                        }else{
                            property.model = tableModel;
                        }
                        property.grid = JSON.stringify(grid); 
                        if(tableModel != 'insert') {
                            property.tablename = baseName;
                            property.id = baseId;
                        };
                        return property;
                    } else {
                        layer.alert('表单名称不能为空！')
                        return false;
                    }
                } else {
                    layer.alert('请配置表单名称行！')
                    return false;
                }

            } else {
                layer.alert('表单内容不能为空！')
                return false;
            }
        }

    //表单详情表格 => 监听表格新增行删除行 
    function addToolListen(){
        table.on('tool('+window.tableId+')', function(obj){
            var event = obj.event;
            if(event == 'addLine'){
                var Data = table.cache[""+window.tableId+""],
                    randomId = createUniqueId(1),
                    datas = { model: "insert", id: randomId };
                for(var i = 0; i < colName.length; i++){
                    datas[colName[i]] = "";
                }
                Data.push(datas);
                table.reload(window.tableId, { data: Data });
                layer.closeAll('tips');
            }else if(event == 'delLine'){
                var Data = table.cache[""+window.tableId+""],
                    index = obj.tr.data('index'),
                    randomId = createUniqueId(1);
                layer.confirm('确认删除？', function(index2){
                    if(obj.data.model == 'normal'){
                        obj.data.model = 'del';
                        delRows.push(obj.data);
                        deleteRow(obj.data, function(res){
                            if(res.retcode == '0'){
                                Data.splice(index, 1);
                                if(index == 0){
                                    var datas = { model: "insert", id: randomId }
                                    for(var i = 0; i < colName.length; i++){
                                        datas[colName[i]] = "";
                                    }
                                    Data.push(datas);
                                } 
                                table.reload(window.tableId,{ data: Data });
                            }
                        }); 
                    }else{
                        Data.splice(index, 1);
                        if(index == 0){
                            var datas = { model: "insert", id: randomId }
                            for(var i = 0; i < colName.length; i++){
                                datas[colName[i]] = "";
                            }
                            Data.push(datas);
                        } 
                        table.reload(window.tableId,{ data: Data });
                    }
                    layer.close(index2);
                });
                layer.closeAll('tips');
            }else if(event == 'check'){
                admin.req({
					url: 'myapi/DC/api/rest/web/custom/GainHistory',
					data: {
						id: obj.data.id
					},
					done: function(res){
						if(res.retcode == '0'){
							if(res.data && res.data.length > 0){
								var taskrecode = layer.open({
									id: 'temporary-addhtml',
									title:'<i class="formFill-icon"></i><span style="color:#FFF;">查看记录</span>',
									offset: '110px',
                                    type: 1,
                                    resize: false,
									shadeClose: true,
									area: ['700px', '450px'],
									success: function(lay, index){
										view(this.id).render('./task/temporary/history', {history: res.data});
									}
								});
							}else{
								layer.msg('暂无记录', {time: 1500});
							}
						}
					}
				})
            }else if(event == 'mustFill'){
                layer.msg('该列不可填报', {time: 1500})
            }
        }) 
    }

    //数组去重
    function handleSame(goodsList){
        for(var i=0; i<goodsList.length; i++){
            var item = goodsList[i]
            for(var j = i+1; j<goodsList.length; j++){
                    if(item.username == goodsList[j].username){
                        goodsList.splice(j,1)
                        i--
                    }                          
            }
        };
        return goodsList;
    }

    //表单详情表格 => 监听单元格编辑
    function changeTab(){
        table.on('edit('+window.tableId+')', function(obj){
            var selector = 'div[lay-id="'+window.tableId+'"] '+obj.tr.selector+' td[data-field="'+obj.field+'"] div';
            var oldVal = $(selector).text(); //获取编辑前的值
            var newVal = obj.value; //得到修改后的值
            var data = obj.data; //得到所在行所有键值
            var Data = table.cache[''+window.tableId+'']; //表格所有信息
            var index = obj.tr.data('index'); //当前编辑行index
            var model = data.model; //当前行的model状态
            var td = 'div[lay-id="'+window.tableId+'"] '+obj.tr.selector+' td[data-field="'+obj.field+'"]';
            var dataType = $(td).attr('lay-event').split(',')[1]; //当前字段的数据类型
            if(newVal != oldVal && model == 'normal'){
                Data[index].model = 'update';   
                table.reload(window.tableId, { data: Data });
            }
            inputVertify(newVal, dataType, selector);
        });
    }

    //字段验证
    function inputVertify(newVal, dataType, selector){
        var reg = null,
            text = '';
        if(dataType == 'integer'){
            reg = /^(([^0][0-9]+|0)\.([0-9]{1,2})$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,2})$)|^(([1-9]+)$)/;
            text = '数字';
        }else if(dataType == 'date'){
            reg = /^(\d{4})-(\d{2})-(\d{2})$/;
            text = '日期';
        }else if(dataType == 'varchar'){
            reg = /^[\u0391-\uFFE5]+$/;
            text = '字符';
        }
        if(dataType != 'varchar'){
            var td = $(selector).parent();
            if(!!$.trim(newVal) && !reg.test($.trim(newVal))){
                layer.msg('该列字段类型为'+text+'格式，请正确输入！', {time: 1500});
                td.attr('style', 'background-color:orange;color:#FFF;')
            }else{
                td.attr('style', 'background-color:transparent;color:#000');
            }
        }
    }

   //按钮点击事件
   $('.T-btn').click(function(){
        var target = $(this).data('target');
        switch (target) {
            case 'export'://导出模板
                var sheet = [],
                    formdata = FormData,
                    url = 'myapi/DC/api/rest/web/custom/exportExcel';
                tools.downLoadfunction(url,{
                    formt_id: formdata[tabIndex].formt_id,
                    taskid: window.taskId, 
                    access_token: layui.data('layuiAdmin').access_token
                });
                break;
            case 'save': 
                var idState = table.cache[''+window.tableId+''],
                    allData = idState ? tools.getTableRow(window.tableId, 'isFill') : [];
                // if(delRows.length > 0){ allData = allData.concat(delRows); }
                for(var i = 0; i < allData.length; i++){
                    delete allData[i].LAY_TABLE_INDEX;
                    delete allData[i].dataplace;
                    delete allData[i].taskid;
                    delete allData[i].statename;
                    allData[i] ? allData[i].id = idState[i].id : '';
                    allData[i] ? allData[i].model = idState[i].model : '';
                }
                var tablebody =  $('#'+window.tableId).next().find('.layui-table-body tbody tr'),
                    flag = true;
                $.each(tablebody, function(i, eachTr){
                    var allTd = eachTr.querySelectorAll('td');
                    $.each(allTd, function(i2, eachTd){
                        if(!eachTd.getAttribute('class')){
                            if(eachTd.getAttribute('style')){ //验证必填项
                                flag = false;
                                return false;
                            }
                            var dataType = eachTd.getAttribute('lay-event').split(',')[1]; //当前字段的数据类型 
                            var reg = null,
                                text = '',
                                newVal = eachTd.querySelector('div').innerText;  
                            if(dataType == 'integer'){
                                reg = /^(([^0][0-9]+|0)\.([0-9]{1,2})$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]{1,2})$)|^(([1-9]+)$)/;
                                text = '数字';
                            }else if(dataType == 'date'){
                                reg = /^(\d{4})-(\d{2})-(\d{2})$/;
                                text = '日期';
                            }
                            if(dataType != 'varchar' && dataType != 'select'){
                                if(newVal.trim() != '' && !reg.test($.trim(newVal))){
                                    eachTd.setAttribute('style','background-color: orange');
                                    flag = false;
                                    layer.msg('该列字段类型为'+text+'格式，请正确输入！', {time: 1500});
                                    return false;
                                }
                            }
                        }
                    })
                })
                if(flag){
                    if(allData && allData.length > 0){
                        admin.req({
                            url: 'myapi/DC/api/rest/web/custom/FormDataOper',
                            type: 'post',
                            data: {
                                griddata: JSON.stringify(allData),
                                tablename: tablename[window.tabIndex],
                                formt_id: formtId[window.tabIndex],
                                taskid: window.taskId,
                                writeid: window.writeId,
                                formdata: '',
                            },
                            success: function(res){
                                if(res.retcode == '0'){
                                    getTaskForm(window.taskId, window.writeId, window.link, '', '', 'true', res.data.dv_results);
                                    handleErrorRow(res.data, allData);
                                    layer.msg('保存成功', {time: 1500});
                                }
                            }
                        })
                    }else{
                        layer.msg('请填写相关数据',{time: 1500});
                    }
                }
            break;
            case 'submit': 
                var idState= table.cache[''+window.tableId+''],
                    allData = idState ? tools.getTableRow(window.tableId, 'checked') : [];
                // if(delRows.length > 0){ allData = allData.concat(delRows); }
                var checkRowData = table.checkStatus(window.tableId).data,
                    options = new Object(),
                    commits = [];
                for(var i = 0; i < allData.length; i++){
                    delete allData[i].LAY_TABLE_INDEX;
                    delete allData[i].dataplace;
                    delete allData[i].taskid;
                    delete allData[i].LAY_CHECKED;
                    delete allData[i].statename;
                    allData[i].id = idState[i].id;
                    allData[i].model = idState[i].model;
                }
                if(checkRowData && checkRowData.length > 0){
                    var flag = true,
                        tablebody =  $('#'+window.tableId).next().find('.layui-table-body tbody tr');
                    $.each(tablebody, function(i, eachTr){
                        var allTd = eachTr.querySelectorAll('td');
                        $.each(allTd, function(i2, eachTd){
                            if(!eachTd.getAttribute('class')){
                                if(eachTd.getAttribute('style')){
                                    flag = false;
                                    return false;
                                }
                            }
                        })
                    })
                    if(flag){
                        layui.each(checkRowData,function(index, item){
                            if(index == 0){
                                options.taskid = window.taskId;
                                options.writeid = window.writeId;
                                options.tablename = tablename[window.tabIndex];
                                options.review = window.review;
                                options.access_token = layui.data('layuiAdmin').access_token;
                                options.formdata = '';
                                options.link = window.link;
                                options.formt_id = formtId[window.tabIndex];
                            }
                            if(item.id){
                                commits.push({id: item.id, state: item.state, writeuser_com_id: item.writeuser_com_id});
                            }
                        })
                        var subData = [],
                            blankData = [],
                            hasBlankLine = false;
                        layui.each(allData, function(index, eachData){
                            for(var i in eachData){
                                if(i != 'id' && i != 'model' && eachData[i]){
                                    subData.push(eachData);
                                    return ;
                                }else{
                                    blankData.push(eachData);
                                    return ;
                                }
                            }
                        })
                        if(subData && subData.length > 0 && blankData.length > 0){
                            hasBlankLine = true;
                        }
                        if(subData && subData.length <= 0){
                            layer.msg('空行数据不能提交', {time: 1500});
                            return ;
                        }
                        options.griddata = JSON.stringify(subData),
                        options.comids = JSON.stringify(commits);
                        layer.open({
                            id: 'usermemo',
                            type: 1,
                            title: '<i class="formFill-icon"></i><span style="color:#FFF;">补充说明</span>',
                            area: ['300px', '290px'],
                            offset: 'auto',
                            shadeClose: true,
                            resize: false,
                            success: function(lay, index){
                                view(this.id).render('./audit/components/usermemo', {
                                    review: window.review,
                                    showReview: true,
                                    title: '提交说明'
                                });
                            },
                            btn: ['确定', '取消'],
                            btnAlign: 'c',
                            yes: function(index, layero){
                                var memoval = $('#usermemo .layui-textarea').val();
                                var isCheck = $('.layui-review-form input[type="radio"]:checked').val();
                                if(isCheck == '0'){
                                    if($.trim(memoval) == ''){
                                        $('#usermemo .layui-textarea').focus();
                                        layer.msg('请填写不复核的原因', {time: 1500});
                                        return false;
                                    }else{
                                        options.usermemo = memoval;
                                        options.review = '0';
                                        saveMemo(options, index, hasBlankLine);
                                    }
                                }else{
                                    options.usermemo = memoval;
                                    saveMemo(options, index, hasBlankLine);
                                }
                             },
                            btn2: function(index, layero){}
                        })
                    }
                }else{
                    layer.msg('请勾选需要提交的表单行', {time: 1500});
                };
            break;
            case 'colla':
                var tbHeight = 0,
                    flag = $(this).find('.layui-icon').hasClass('layui-icon-up');
                $('.left-card').slideToggle();
                $('.right-card').slideToggle();
                $(this).find('i').toggleClass("layui-icon-up layui-icon-down");
                $(this).parents('.select-form-box').toggleClass('height-auto height-max');
                tbHeight = flag ? 700 : 250;
                table.reload(window.tableId, {
                    height: tbHeight
                });
            break;
            case 'save-kq':
                var tid = $('.formFillKqTable').data('id');
                var args = {checking: '1', taskid: tid};
                var usersArr = [];
                $('#fill-form-kqform').find('.formFillKqTableBox1 tbody .T-firstTr').each(function(index, el) {
                    var $basic = $(el).find('.trbasic');
                    var basicInfo = tools.getAreaArgs($basic);
                    var datesInfo = [];
                    $('#fill-form-kqform').find('.formFillKqTableBox2 tbody .T-firstTr').eq(index).each(function(oIndx,oEl){
                        $(oEl).find('.T-dateInfo').each(function(d, del) {
                            datesInfo.push(tools.getAreaArgs($(del)));
                        });
                        $(oEl).next().find('.T-dateInfo').each(function(d, del) {
                            datesInfo.push(tools.getAreaArgs($(del)));
                        });
                    
                    })   
                    basicInfo.users_time = datesInfo;
                    usersArr.push(basicInfo);
                });
                args.users = JSON.stringify(usersArr);
                admin.req({
                    url: 'myapi/DC/api/rest/web/custom/FormDataOper',
                    type: 'post',
                    data: args,
                    success: function(res){
                        if(res.retcode == '0'){
                            layer.msg('保存成功', {time: 1500});
                            getKQTaskForm(window.taskId, window.writeId);
                        }
                    }
                });
            break;
            case 'submit-kq':  
            var tid = $('.formFillKqTable').data('id'),
                args = {checking: '1', taskid: tid},
                usersArr = [],writeIds = [],
                isNeedCheck = false;
                $('#fill-form-kqform').find('.formFillKqTableBox1 tbody .T-firstTr').each(function(index, el) { 
                    if(!$(el).find('.T-isChecked').is(':checked')) {
                        return true;
                    }
                    var $basic = $(el).find('.trbasic');
                    var basicInfo = tools.getAreaArgs($basic); 
                    writeIds.push(basicInfo.writeid);
                    var datesInfo = [];    
                    $('#fill-form-kqform').find('.formFillKqTableBox2 tbody .T-firstTr').eq(index).each(function(oIndx,oEl){
                            $(oEl).find('.T-dateInfo').each(function(d, del) {
                                datesInfo.push(tools.getAreaArgs($(del)));
                            });
                            $(oEl).next().find('.T-dateInfo').each(function(d, del) {  
                                datesInfo.push(tools.getAreaArgs($(del)));
                            }); 
                    
                    })  
                    basicInfo.users_time = datesInfo;
                    if(basicInfo.checkingstate === '1') {
                        isNeedCheck = true;
                    }
                    usersArr.push(basicInfo);
                });
                if(usersArr.length === 0) {
                    layer.msg('请选择数据', {time: 1500});
                    return false;
                }
                args.users = JSON.stringify(usersArr);
                args.writeids = JSON.stringify(writeIds); 
                isNeedCheck=true;
                if(isNeedCheck) {
                    layer.open({
                        id: 'auditusermemo',
                        type: 1,
                        title: '<i class="formFill-icon"></i><span style="color:#FFF;">提交表单</span>',
                        area: ['500px', '340px'],
                        offset: 'auto',
                        shadeClose: true,
                        resize: false,
                        success: function(lay, index){
                            view(this.id).render('./fill/components/auditInfo', {taskid: tid});
                        },
                        btn: ['确定', '取消'],
                        btnAlign: 'c',
                        yes: function(index, layero){
                            args.usermemo = $('#auditusermemo textarea[name="memo"]').val();
                            args.usermsg = $('#auditusermemo input[name="usermsgdata"]').val();  
                            if( JSON.parse(args.usermsg).length>0){
                                admin.req({
                                    url: 'myapi/DC/api/rest/web/custom/DataCommit',
                                    type: 'post',
                                    data: args,
                                    success: function(res){ 
                                        if(res.retcode == '0'){
                                            layer.close(index); 
                                            getKQTaskForm(window.taskId, window.writeId, success = function(res){  
                                                var data =  res.data.data.data;
                                                if(res.data.retcode == 0 && data.users && data.users.length == 0){ 
                                                    getTaskTable();
                                                    $('.formFillkqTable').empty();
                                                }
                                            });
                                            layer.msg('提交成功', {time: 1500});
                                        }
                                    }
                                });
                            }else{
                                layer.msg("请选择审核人！",{time:1000})
                            }
                          
                        }
                    });
                }else {
                    layer.open({
                        id: 'usermemo',
                        type: 1,
                        title: '<i class="formFill-icon"></i><span style="color:#FFF;">提交表单</span>',
                        area: ['300px', '250px'],
                        offset: 'auto',
                        shadeClose: true,
                        resize: false,
                        success: function(lay, index){
                            view(this.id).render('./audit/components/usermemo');
                        },
                        btn: ['确定', '取消'],
                        btnAlign: 'c',
                        yes: function(index, layero){
                            args.usermemo = $('#usermemo .layui-textarea').val();
                            admin.req({
                                url: 'myapi/DC/api/rest/web/custom/DataCommit',
                                type: 'post',
                                data: args,
                                success: function(res){
                                    if(res.retcode == '0'){
                                        layer.close(index);
                                        layer.msg('提交成功', {time: 1500});
                                        getKQTaskForm(window.taskId, window.writeId, success = function(res){   
                                            var data =  res.data.data.data;  
                                            res.data.retcode == 0 && data.users && data.users.length == 0&&getTaskTable();    
                                        }); 
                                    }
                                }
                            });
                        }
                    })
                };
            break;
            default:
            break;
        }
   })

    //待办任务点击事件
    $('.task-ul').delegate('li.T-btn', 'click', function(){
        var toJump = $(this).attr('data-jump');
        location.hash = search.redirect ? decodeURIComponent(search.redirect) : '/'+toJump;
    })
    

    //导入数据
    var uploadInst = upload.render({
        elem: '#btn-import',
        url: 'myapi/DC/api/rest/web/custom/imporExcel?access_token='+layui.data('layuiAdmin').access_token,
        accept: 'file',
        data: {
            id: function(){
                return formtId[window.tabIndex]
            },
            taskid: function(){
                return window.taskId
            },
            writeid: function(){
                return window.writeId
            },
            dataplace: function(){
                return 'grid'
            },
            access_token: function(){
                return layui.data('layuiAdmin').access_token
            }
        },
        before: function(obj){
            layer.load(1);
        },
        done: function(res, index, upload){ 
            var warnMsg = res.errorList && res.errorList.length > 0 ? handleErrorList(res.errorList) : res.retmsg;
            if(res.retcode  == 0){ getTaskForm(window.taskId, window.writeId, window.link); }
            else if(res.retcode == -2){ admin.exit(); }
            layer.msg(warnMsg, {time: 4000});
            layer.closeAll('loading');
        },
        error: function(index, upload){
            layer.closeAll('loading');
            uploadInst.upload(); 
        }
    })

    /*@method 处理导入失败的提示信息
    */
    function handleErrorList(errorList){
        var msg = '';
        layui.each(errorList, function(index, item){
            msg += '<div class="errorItem">错误行：'+item.row+'，'+item.msg+'</div>';
        });
        return msg;
    }

    //保存备注
    function saveMemo(options, index, blank){
        admin.req({
            url: 'myapi/DC/api/rest/web/custom/DataCommit',
            type: 'post',
            data: options,
            success: function(res){
                if(res.retcode == 0){
                    var msg = '';
                    blank ? msg = '提交成功，已忽略空行' : msg = '提交成功';
                    layer.msg(msg, {time: 1500});
                    layer.close(index);
                    getTaskForm(window.taskId, window.writeId, window.link); //提交刷新表格
                }
            }
        })
    }   

    //生成唯一id
    function createUniqueId(n) {
        var random = function() { // 生成10-12位不等的字符串
            return Number(Math.random().toString().substr(2)).toString(36); // 转换成十六进制
        }
        var arr = [];
        function createId() {
            var num = random();
            var bool = false;
            for(var i = 0; i < arr.length; i++){
                if(arr[i] === num){
                    bool = true
                }
            }
            if(bool) {
                createId();
            }else {
                arr.push(num);
            }
        }
        var i = 0;
        while(i < n) {
            createId();
            i++;
        }
        return arr[0];
    }

    //删除表单详情表单行
    function deleteRow(row, payload){
        if(row.id){
            delete row.dataplace;
            delete row.taskid;
        }
        row.model = 'del';
        admin.req({
            url: 'myapi/DC/api/rest/web/custom/FormDataOper',
            type: 'post',
            data: {
                griddata: JSON.stringify([row]),
                tablename: tablename[window.tabIndex],
                taskid: window.taskId,
                formt_id: formtId[window.tabIndex],
                formdata: ''
            },
            success: function(res){
                if(res.retcode == '0'){
                    payload(res);
                    layer.msg('删除成功', {time: 1500});
                }
            }
        })
    }

    /*处理保存出错的表单行
    @param failData 错误数据
    @param data 当前保存表格所有数据
    */
    function handleErrorRow(failData, data){
        var idsArray = failData.ids.split(','),
            errorTds = failData.dv_results;
        if(idsArray && idsArray.length > 0){
            for(var i = 0; i < idsArray.length; i++){
                for(var j = 0; j < data.length; j++){
                    if(idsArray[i] == data[j].id){
                        var elem = $('#'+window.tableId).next(),
                            tr = elem.find('.layui-table-box tbody tr[data-index="'+j+'"]');
                        tr.addClass('errorLine');
                    }
                }
            }
        }
    }

    

});
</script>